package cn.micai.base.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

/**
 * 描述：How to delete non empty directory in java
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/6/7 10:54
 */
public class DeleteNonEmptyDirectoryMain {

    public static void main(String [] args) {
        System.out.println("Deleting using recursion");
        System.out.println("---------------");
        File folder= new File("D://workspace_spring_1");
        // Using recusrion
        try {
            delete(folder);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("---------------");
        System.out.println("Deleting using Apache IO");
        File folder2= new File("D://workspace_spring_2");
        deleteUsingApacheIO(folder2);
        System.out.println("Deleting folder : " + folder2.getAbsolutePath());

    }

    // Delete using recursion(递归)
    public static void delete(File file) throws IOException {
        if (file.isDirectory()) {
            // We can directly delete if we found empty directory
            if (file.list().length == 0) {
                file.delete();
                System.out.println("Deleting folder : " + file.getAbsolutePath());
            } else {
                // list all the files in directly
                File[] files = file.listFiles();
                for (File temp : files) {
                    // recursive delete
                    delete(temp);
                }
                // Check directory again, if we find it empty, delete it
                if (file.list().length == 0) {
                    file.delete();
                    System.out.println("Deleting folder : " + file.getAbsolutePath());
                }
            }
        } else {
            // if file, then we can directly delete it
            file.delete();
            System.out.println("Deleting file  : " + file.getAbsolutePath());
        }
    }

    // Delete using Apache common IO
    public static void deleteUsingApacheIO(File file) {
        try {
            FileUtils.deleteDirectory(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
